<template>
  <div class="container">
    <el-row :gutter="40">
      <el-col :span="6">
        <!-- 部门的树形结构 -->
        <el-tree :data="data" style="margin-top: 40px"/>
      </el-col>
      <el-col :span="18">
        <!--工具条-->
        <el-form :inline="true" :model="filters" style="margin-top:40px" class="demo-form-inline">
          <div class="search">
            <el-form-item label="部门名称">
              <el-input v-model="filters.department" placeholder="请输入你要查询的部门名称"/>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="getDepartmentsByFilter">查询</el-button>
            </el-form-item>
          </div>
          <div class="newButton">
            <el-form-item>
              <el-button type="primary" @click="handleAdd">新增</el-button>
            </el-form-item>
          </div>
        </el-form>
        <!--列表-->
        <el-table v-loading="listLoading" :data="department" highlight-current-row @selection-change="selsChange">
          <el-table-column type="selection" width="55"/>
          <el-table-column type="index" width="60"/>
          <el-table-column prop="department" label="部门编码" width="160" sortable/>
          <el-table-column prop="description" label="部门名称" width="160" sortable/>
          <el-table-column prop="parentDescription" label="父级部门" width="160" sortable/>
          <el-table-column :formatter="formatAvailable" prop="available" label="部门状态" width="160" sortable/>
          <!-- <el-table-column prop="sort" label="排序序号" width="120" sortable/> -->
          <el-table-column prop="createTime" label="添加时间" width="160" sortable/>
          <el-table-column label="操作" width="270">
            <template slot-scope="scope">
              <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <span v-if="scope.row.available === false">
                <el-button size="small" type="info" @click="handleAvailable(scope.$index, scope.row)">改为工作</el-button>
              </span>
              <span v-else>
                <el-button size="small" type="success" @mouseover="mouseover()" @click="handleAvailable(scope.$index, scope.row)">改为休假</el-button>
              </span>
              <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!--工具条-->
        <el-col :span="24" style="background-color: aliceblue">
          <div style="margin:10px">
            <el-button :disabled="sels.length===0" type="danger" @click="batchRemove" >批量删除</el-button>
            <el-pagination
              :total="total"
              :current-page="page"
              :page-size="5"
              :page-sizes="[3, 5, 10, 20]"
              layout="total, sizes, prev, pager, next, jumper"
              style="float:right;padding:5px 0"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"/>
          </div>
        </el-col>
      </el-col>
    </el-row>
    <!--编辑界面-->
    <el-dialog :visible.sync="editFormVisible" :close-on-click-modal="false" title="编辑">
      <el-form ref="editForm" :rules="editFormRules" :model="editForm" label-width="80px">
        <el-form-item label="部门编码" prop="department">
          <el-input v-model="editForm.department" auto-complete="off"/>
        </el-form-item>
        <el-form-item label="部门名称" prop="description">
          <el-input v-model="editForm.description" type="textarea"/>
        </el-form-item>
        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="editForm.sort"/>
        </el-form-item>
        <!-- 点击弹出处理 -->
        <el-form-item label="父级部门" prop="parentDescription">
          <el-input v-model="editForm.parentDescription" auto-complete="off" @focus="openParentDepartmentTree()"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="editFormVisible = false">取消</el-button>
        <el-button :loading="editLoading" type="primary" @click.native="editSubmit">提交</el-button>
      </div>
    </el-dialog>
    <!--新增界面-->
    <el-dialog :visible.sync="addFormVisible" :close-on-click-modal="false" title="新增" >
      <el-form ref="addForm" :rules="addFormRules" :model="addForm" label-width="80px">
        <el-form-item label="部门名称" prop="department">
          <el-input v-model="addForm.department" auto-complete="off"/>
        </el-form-item>
        <el-form-item label="部门简述" prop="description">
          <el-input v-model="addForm.description" auto-complete="off"/>
        </el-form-item>
        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="addForm.sort"/>
        </el-form-item>
        <el-form-item label="父级部门" prop="parentDescription">
          <el-input v-model="addForm.parentDescription" auto-complete="off" @focus="openParentDepartmentTree()"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="addFormVisible = false">取消</el-button>
        <el-button :loading="addLoading" type="primary" @click.native="addSubmit">提交</el-button>
      </div>
    </el-dialog>
    <!-- 上级部门选择（树形结构） -->
    <el-dialog :visible.sync="departmentsFormVisible" :close-on-click-modal="false" title="上级部门选择" style="z-index:9999;">
      <div class="block">
        <el-tree
          ref="treeDepartments"
          :props="treeDepartments"
          :data="parentIdData"
          :check-strictly="true"
          :highlight-current="true"
          :expand-on-click-node="false"
          node-key="id"
          show-checkbox
          default-expand-all
          @check-change="checkChange"
          @node-click="nodeClick">
          <span slot-scope="{ node }" class="custom-tree-node">
            <span>{{ node.label }}</span>
          </span>
        </el-tree>
        <div slot="footer" class="dialog-footer" style="dispaly:block;text-align:center">
          <el-button :loading="departmentsLoading" type="primary" size="mini" @click.native="addDepartmentsSubmit">提交</el-button>
          <el-button size="mini" style="margin-right:50px;margin-top:20px" @click.native="departmentsFormVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartmentTree, getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment, getFilterDepartment, availableDepartment } from '../../../api/department'

export default {

  data() {
    return {
      available: false,
      filters: {
        department: ''
      },
      flag: 0,
      treeDepartments: [],
      parentIdData: '', // 后台返回的上级角色树
      department: [],
      oldDepartment: '',
      page: 1,
      size: 5,
      total: 1,
      listLoading: false,
      sels: [], // 列表选中列
      data: [],
      parentDepartment: '',

      editFormVisible: false, // 编辑界面是否显示
      editLoading: false,
      departmentsFormVisible: false,
      departmentsLoading: false,
      editFormRules: {
        department: [{ required: true, message: '请添加部门名称', trigger: 'blur' }]
      },
      // 编辑界面数据
      editForm: {
        department: '',
        description: '',
        parentId: '',
        parentDescription: '',
        sort: ''
      },

      addFormVisible: false, // 新增界面是否显示
      addLoading: false,
      addFormRules: {
        department: [{ required: true, message: '请添加部门名称', trigger: 'blur' }]
      },
      // 新增界面数据
      addForm: {
        department: '',
        description: '',
        parentId: '',
        parentDescription: '',
        sort: ''
      }
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree2.filter(val)
    }
  },
  mounted() {
    this.getDepartments()
    this.getTree()
    this.getparentDepartments()
  },
  methods: {
    formatAvailable: function(row, column) {
      return row.available === true ? '工作中' : row.available === false ? '休假中' : '未知'
    },
    getDepartmentsByFilter() {
      const para = {
        department: this.filters.department === undefined ? '' : this.filters.department,
        page: this.page === undefined ? '' : this.page,
        size: this.size === undefined ? '' : this.size
      }
      if (this.oldDepartment !== this.filters.department) {
        para.page = 1
        this.page = 1
        this.oldDepartment = this.filters.department
      }
      getFilterDepartment(para).then((res) => {
        this.page = res.data.current
        this.size = res.data.size
        this.total = res.data.total
        this.department = res.data.list
        this.listLoading = false
      })
    },
    getDepartments() {
      const para = {
        page: this.page === undefined ? '' : this.page,
        size: this.size === undefined ? '' : this.size
      }
      this.listLoading = true
      getDepartmentListPage(para.page, para.size).then((res) => {
        this.department = res.data.list
        this.page = res.data.current
        this.total = res.data.total
        this.size = res.data.size
        this.listLoading = false
      })
    },
    openParentDepartmentTree() {
      this.departmentsFormVisible = true
    },
    checkChange(item, node, self) {
      if (node === true) { // 点击未选中复选框
        this.editCheckId = item.id
        this.$refs.treeDepartments.setCheckedKeys([item.id])
      } else {
        if (this.editCheckId === item.id) {
          this.$refs.treeDepartments.setCheckedKeys([])
        }
      }
    },
    nodeClick(item, node, self) {
      this.editCheckId = item.id
      this.$refs.treeDepartments.setCheckedKeys([item.id])
    },
    selectDepartment() {
      this.parentDescription = this.$refs.treeDepartments.getCheckedNodes()[0].label
      this.parentId = this.$refs.treeDepartments.getCheckedNodes()[0].id
      this.departmentsLoading = true
    },
    // 选择父级部门
    addDepartmentsSubmit: function() {
      if (this.$refs.treeDepartments.getCheckedNodes().length !== 0) { // 只选择一个上级
        if (this.flag === 0) {
          this.selectDepartment()
          this.addForm.parentDescription = this.parentDescription
          this.departmentsLoading = false
          this.departmentsFormVisible = false
        } else {
          this.selectDepartment()
          this.editForm.parentDescription = this.parentDescription
          this.departmentsLoading = false
          this.departmentsFormVisible = false
        }
      } else { // 取消当前选择的上级
        if (this.flag === 0) {
          this.addForm.parentDescription = ''
          this.departmentsLoading = false
          this.departmentsFormVisible = false
        } else {
          this.editForm.parentDescription = ''
          this.departmentsLoading = false
          this.departmentsFormVisible = false
        }
      }
    },
    // 获取部门树结构
    getparentDepartments() {
      getDepartmentTree().then((res) => {
        this.parentIdData = res.data
      })
    },
    // 改变每页显示条数时根据有无查询条件来选择接口
    handleSizeChange(val) {
      this.size = val
      if (this.filters.department !== '' || this.filters.department !== undefined) {
        this.getDepartmentsByFilter()
      } else {
        this.getDepartments()
      }
    },
    selsChange: function(sels) {
      this.sels = sels
    },
    handleCurrentChange(val) {
      this.page = val
      if (this.filters.department !== '' && this.filters.department !== undefined) {
        this.getDepartmentsByFilter()
      } else {
        this.getDepartments()
      }
    },
    getTree() {
      getDepartmentTree().then((res) => {
        this.data = res.data
      })
    },
    // 改为工作中/改为休假中 状态变更
    handleAvailable: function(index, row) {
      this.$confirm('此操作会级联到下级部门，确认执行吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        const para = {
          id: row.id,
          available: row.available
        }
        availableDepartment(para).then((res) => {
          this.listLoading = false
          this.$message({
            message: '操作成功',
            type: 'success'
          })
          this.getDepartments()
          this.getTree()
          this.getparentDepartments()
        })
      }).catch(() => {

      })
    },
    // 删除
    handleDel: function(index, row) {
      this.$confirm('删除部门会级联删除子部门，您确定要删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        const para = { id: row.id }
        removeDepartment(para).then((res) => {
          this.listLoading = false
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getDepartments()
          this.getTree()
          this.getparentDepartments()
        })
      }).catch(() => {

      })
    },
    // 批量删除
    batchRemove: function() {
      var idsString = this.sels.map(item => item.id).toString()
      var ids = idsString.split(',')
      this.$confirm('删除部门会级联删除子部门，您确定要删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true
        const para = { ids: ids }
        batchRemoveDepartment(para).then((res) => {
          this.listLoading = false
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getDepartments()
          this.getTree()
          this.getparentDepartments()
        })
      }).catch(() => {

      })
    },
    // 显示新增界面
    handleAdd: function() {
      this.addFormVisible = true
      this.addForm = {
        department: '',
        description: '',
        parentId: '',
        parentDepartment: '',
        sort: ''
      }
      this.flag = 0
    },
    // 显示编辑界面
    handleEdit: function(index, row) {
      this.editFormVisible = true
      this.editForm = Object.assign({}, row)
      this.flag = 1
    },
    // 编辑
    editSubmit: function() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.editLoading = true
            const para = Object.assign({}, this.editForm)
            const myPara = {
              createTime: para.createTime,
              department: para.department,
              description: para.description,
              id: para.id,
              sort: para.sort,
              parentId: para.parentId
            }
            // myPara.parentId = this.$refs.treeDepartments.getCheckedNodes().length === 0 ? '0' : this.$refs.treeDepartments.getCheckedNodes()[0].id
            // 老是有 undefined问题  this.$refs.treeDepartments，this.$refs.treeDepartments.getCheckedNodes()[0]
            if (this.$refs.treeDepartments !== undefined) {
              if (this.$refs.treeDepartments.getCheckedNodes()[0] !== undefined) {
                myPara.parentId = this.$refs.treeDepartments.getCheckedNodes()[0].id
              }
            }
            editDepartment(myPara).then((res) => {
              this.editLoading = false
              this.$message({
                message: '提交成功',
                type: 'success'
              })
              this.$refs['editForm'].resetFields()
              if (this.$refs.treeDepartments !== undefined) {
                this.$refs.treeDepartments.setCheckedKeys([])
              }
              this.editFormVisible = false
              this.getDepartments()
              this.getTree()
              this.getparentDepartments()
            })
          })
        }
      })
    },
    // 新增
    addSubmit: function() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.addLoading = true
            const para = Object.assign({}, this.addForm)
            const myPara = {
              department: para.department,
              description: para.description,
              sort: para.sort,
              parentId: para.parentId
            }
            myPara.parentId = this.$refs.treeDepartments === undefined ? '' : this.$refs.treeDepartments.getCheckedNodes()[0] === undefined ? '' : this.$refs.treeDepartments.getCheckedNodes()[0].id
            addDepartment(myPara).then((res) => {
              this.addLoading = false
              this.$message({
                message: '提交成功',
                type: 'success'
              })
              this.$refs['addForm'].resetFields()
              this.addFormVisible = false
              this.getDepartments()
              this.getTree()
            })
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
  .container{
    width: 94%;
    margin-left: 3%;
    height: 100%;
  }
  .el-dialog{
    width: 800px
  }
  .search {
    background-color: white;
    width: 100%;
    height: 100%;
    padding: 20px 20px 0 20px;
    margin-bottom: 30px
  }
  .newButton {
    background-color: white;
    width: 100%;
    height: 100%;
    padding: 20px 20px 0 20px;
    .el-form-item {
      margin-bottom: 0px
    }
  }
</style>
<style>
  .el-message-box{
    width: 430px;
  }
</style>

